package com.news.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.news.db.OpDB;
import com.news.model.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/registServlet")
public class RegistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.判断数据库是否有用户名
        OpDB opdb = new OpDB();
        boolean flag = opdb.OpGetUsername(username);
        //3.判断标记
        ResultInfo info = new ResultInfo();
        if (flag){
            info.setFlag(false);
            info.setError("此用户名太受欢迎，请更换一个用户名！");
        }else {
            opdb.OpAddUser(username,password);
            info.setFlag(true);
        }
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(info);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }
}
